/**
 * Created By zhangQ 2018/2/14
 */
import types from './mutations-types'
import Cookies from 'js-cookie'
import { loginByUsername } from '@api/common/user'

let actions = {
  doLogin ({ commit }, userInfo) {
    let username = userInfo.username.trim()
    return new Promise((resolve, reject) => {
      loginByUsername(username, userInfo.password).then(response => {
        if (response.data.isSuccess === 1) {
          let resData = response.data
          // 提交Token 1.在cookie中先保存
          Cookies.set('token', resData.data.token)
          commit(types.setCurrentToken, resData.data.token)
          // 提交当前用户信息
          let userInfo = resData.data.user
          userInfo.role = resData.data.role
          userInfo.permission = resData.data.permission
          commit(types.setCurrentUser, userInfo)
          resolve(response)
        } else {
          resolve(response)
        }
      }).catch(error => {
        reject(error)
      })
    })
  },
  setActiveMenu ({ commit }, name) {
    commit(types.setActiveMenu, name)
  },
  logout ({ commit }) {
    Cookies.remove('token')
    commit(types.setCurrentToken, '')
    // 提交当前用户信息
    commit(types.setCurrentUser, {
      userId: '',
      loginName: '',
      mobile: '',
      email: '',
      realName: '',
      headIco: '',
      companyName: '',
      legaler: '',
      status: '',
      parentUser: '',
      role: [], // 用户角色
      permission: [] // 用户权限
    })
  }
}

export default actions
